import sys
import os
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                            QLabel, QListWidget, QPushButton, QFileDialog,
                            QMessageBox, QProgressBar, QSplitter, QFrame,
                            QSlider, QSpinBox, QGroupBox, QListWidgetItem,
                            QScrollArea, QComboBox, QSizePolicy)  # 确保 QSizePolicy 在这里
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QPixmap, QFont, QPalette, QColor

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import io
import glob

# 修改导入方式
from components.controller import MainController
from models.data_models import DetectionResult, ImageInfo
from ui.image_viewer import ImageViewer


class MainWindow(QMainWindow):
    """主窗口类"""

    def __init__(self):
        super().__init__()
        self.controller = MainController()
        self.current_detection_result = None
        self.weights_folder = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "weights")

        # 设置窗口基本属性
        self.setWindowTitle("天牛目标检测与计数系统")
        self.setGeometry(100, 100, 1400, 950)
        self.setMinimumSize(1200, 900)

        # 初始化UI
        self._init_ui()
        self._connect_signals()
        self._setup_styles()

        # 尝试加载中文字体
        self._init_font()

        # 自动扫描模型文件
        self._scan_model_files()

        # 自动加载模型
        self.load_default_model()

    def _init_font(self):
        """初始化中文字体"""
        self.font_path = None
        # 常见的中文字体路径
        font_paths = [
            "C:/Windows/Fonts/msyh.ttc",  # 微软雅黑
            "C:/Windows/Fonts/simhei.ttf",  # 黑体
            "C:/Windows/Fonts/simsun.ttc",  # 宋体
        ]

        for path in font_paths:
            if os.path.exists(path):
                self.font_path = path
                break

        if not self.font_path:
            print("警告: 未找到中文字体，将使用默认字体")

    def _init_ui(self):
        """初始化用户界面"""
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        main_layout.setSpacing(10)
        main_layout.setContentsMargins(10, 10, 10, 10)

        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(splitter)

        # 左侧面板（原右侧面板）
        left_panel = self._create_left_panel()
        splitter.addWidget(left_panel)

        # 中央图像显示区域
        center_panel = self._create_center_panel()
        splitter.addWidget(center_panel)

        # 设置分割器比例
        splitter.setSizes([300, 1100, 0])  # 左侧面板300，中央面板1100，右侧面板0

        # 创建状态栏
        self.statusBar().showMessage("欢迎使用天牛目标检测与计数系统")

    def _create_left_panel(self) -> QWidget:
        """创建右侧控制面板"""
        panel = QFrame()
        panel.setFrameStyle(QFrame.StyledPanel)
        panel.setMaximumWidth(320)
        panel.setMinimumWidth(280)

        layout = QVBoxLayout(panel)
        layout.setSpacing(15)

        # 模型加载区域
        model_group = QGroupBox("模型设置")
        model_layout = QVBoxLayout(model_group)

        # 模型选择下拉框
        model_select_layout = QHBoxLayout()
        model_select_layout.addWidget(QLabel("选择模型:"))
        self.model_combo = QComboBox()
        self.model_combo.setMinimumHeight(30)
        model_select_layout.addWidget(self.model_combo)
        model_layout.addLayout(model_select_layout)

        # 第二行按钮：加载选中模型（单独一行）
        self.load_selected_btn = QPushButton("加载选中模型")
        self.load_selected_btn.setMinimumHeight(35)
        model_layout.addWidget(self.load_selected_btn)

        # 模型状态显示
        self.model_status_label = QLabel("未加载模型")
        self.model_status_label.setStyleSheet("color: #666666; font-style: italic;")
        self.model_status_label.setWordWrap(True)
        model_layout.addWidget(self.model_status_label)

        layout.addWidget(model_group)

        # 图像操作区域
        image_group = QGroupBox("图像操作")
        image_layout = QVBoxLayout(image_group)

        # 图像打开按钮布局 - 放在同一行
        image_open_layout = QHBoxLayout()
        self.open_image_btn = QPushButton("打开单张图像")
        self.open_image_btn.setMinimumHeight(35)
        image_open_layout.addWidget(self.open_image_btn)

        self.open_batch_btn = QPushButton("批量打开图像")
        self.open_batch_btn.setMinimumHeight(35)
        image_open_layout.addWidget(self.open_batch_btn)
        image_layout.addLayout(image_open_layout)

        # 清空按钮单独一行
        self.clear_btn = QPushButton("清空图像队列")
        self.clear_btn.setMinimumHeight(35)
        image_layout.addWidget(self.clear_btn)

        layout.addWidget(image_group)

        # 检测操作区域
        detect_group = QGroupBox("检测操作")
        detect_layout = QVBoxLayout(detect_group)

        # 检测按钮布局 - 放在同一行
        detect_buttons_layout = QHBoxLayout()
        self.detect_current_btn = QPushButton("检测当前图像")
        self.detect_current_btn.setMinimumHeight(35)
        detect_buttons_layout.addWidget(self.detect_current_btn)

        self.detect_batch_btn = QPushButton("批量检测所有")
        self.detect_batch_btn.setMinimumHeight(35)
        detect_buttons_layout.addWidget(self.detect_batch_btn)
        detect_layout.addLayout(detect_buttons_layout)

        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        detect_layout.addWidget(self.progress_bar)

        layout.addWidget(detect_group)

        # 图像列表
        list_group = QGroupBox("图像队列")
        list_layout = QVBoxLayout(list_group)

        self.image_list = QListWidget()

        # 设置大小策略让列表跟随父组件变化
        from PyQt5.QtWidgets import QSizePolicy
        self.image_list.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # 设置一个合理的最小高度，避免太小
        self.image_list.setMinimumHeight(150)

        list_layout.addWidget(self.image_list)
        layout.addWidget(list_group)

        # 设置布局伸缩因子，让图像列表占据剩余空间
        layout.setStretchFactor(model_group, 0)
        layout.setStretchFactor(image_group, 0)
        layout.setStretchFactor(detect_group, 0)
        layout.setStretchFactor(list_group, 1)  # 图像列表占据剩余空间

        return panel

    def _create_center_panel(self) -> QWidget:
        """创建中央图像显示面板"""
        panel = QFrame()
        panel.setFrameStyle(QFrame.StyledPanel)

        layout = QVBoxLayout(panel)
        layout.setContentsMargins(5, 5, 5, 5)

        # 图像查看器
        self.image_viewer = ImageViewer()
        self.image_viewer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 设置大小策略为扩展
        layout.addWidget(self.image_viewer)

        # 图像导航按钮区域
        nav_layout = QHBoxLayout()
        nav_layout.setSpacing(10)
        nav_layout.setContentsMargins(20, 10, 20, 10)

        # 前一张按钮
        self.prev_image_btn = QPushButton("◀ 前一张")
        self.prev_image_btn.setMinimumHeight(35)
        self.prev_image_btn.setMaximumWidth(120)
        self.prev_image_btn.setEnabled(False)
        nav_layout.addWidget(self.prev_image_btn)

        # 图片信息标签
        self.image_info_label = QLabel("无图像")
        self.image_info_label.setAlignment(Qt.AlignCenter)
        self.image_info_label.setStyleSheet("color: #666666; font-size: 12px;")
        nav_layout.addWidget(self.image_info_label)

        # 后一张按钮
        self.next_image_btn = QPushButton("后一张 ▶")
        self.next_image_btn.setMinimumHeight(35)
        self.next_image_btn.setMaximumWidth(120)
        self.next_image_btn.setEnabled(False)
        nav_layout.addWidget(self.next_image_btn)

        layout.addLayout(nav_layout)

        return panel

    def _create_right_panel(self) -> QWidget:
        """创建右侧信息面板"""
        panel = QFrame()
        panel.setFrameStyle(QFrame.StyledPanel)
        panel.setMaximumWidth(0)  # 设置最大宽度为0，使其不可见
        panel.setMinimumWidth(0)  # 设置最小宽度为0，使其不可见

        layout = QVBoxLayout(panel)
        layout.setContentsMargins(5, 5, 5, 5)

        return panel

    def _connect_signals(self):
        """连接信号槽"""
        # 模型相关按钮信号
        self.load_selected_btn.clicked.connect(self.load_selected_model)

        # 按钮信号
        self.open_image_btn.clicked.connect(self.open_single_image)
        self.open_batch_btn.clicked.connect(self.open_batch_images)
        self.clear_btn.clicked.connect(self.clear_images)
        self.detect_current_btn.clicked.connect(self.detect_current_image)
        self.detect_batch_btn.clicked.connect(self.detect_batch_images)

        # 图像列表选择
        self.image_list.currentRowChanged.connect(self._on_image_selected)

        # 控制器信号
        self.controller.detection_completed.connect(self._on_detection_completed)
        self.controller.batch_progress_updated.connect(self._on_batch_progress)
        self.controller.batch_completed.connect(self._on_batch_completed)
        self.controller.error_occurred.connect(self._on_error_occurred)
        self.controller.status_updated.connect(self._on_status_updated)

        # 图像导航按钮信号
        self.prev_image_btn.clicked.connect(self.go_to_previous_image)
        self.next_image_btn.clicked.connect(self.go_to_next_image)

    def _setup_styles(self):
        """设置样式"""
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f0f0;
            }
            QGroupBox {
                font-weight: bold;
                border: 2px solid #cccccc;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 8px 0 8px;
            }
            QPushButton {
                background-color: #4CAF50;
                border: none;
                color: white;
                padding: 8px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3d8b40;
            }
            QPushButton:disabled {
                background-color: #cccccc;
                color: #666666;
            }
            QComboBox {
                border: 2px solid #cccccc;
                border-radius: 6px;
                padding: 5px 10px;
                background-color: white;
                color: #333333;
                font-size: 13px;
                min-height: 20px;
            }
            QComboBox:hover {
                border-color: #4CAF50;
            }
            QComboBox:focus {
                border-color: #2196F3;
                background-color: #f8f9fa;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 20px;
                border-left-width: 1px;
                border-left-color: #cccccc;
                border-left-style: solid;
                border-top-right-radius: 6px;
                border-bottom-right-radius: 6px;
                background-color: #f5f5f5;
            }
            QComboBox::drop-down:hover {
                background-color: #e8f5e8;
            }
            QComboBox::down-arrow {
                width: 0px;
                height: 0px;
                border-left: 4px solid transparent;
                border-right: 4px solid transparent;
                border-top: 6px solid #666666;
            }
            QComboBox::down-arrow:hover {
                border-top-color: #4CAF50;
            }
            QComboBox QAbstractItemView {
                border: 2px solid #cccccc;
                border-radius: 6px;
                background-color: white;
                selection-background-color: #e3f2fd;
                selection-color: #1976d2;
                padding: 4px;
            }
            QComboBox QAbstractItemView::item {
                min-height: 25px;
                padding: 4px 8px;
                border-bottom: 1px solid #eeeeee;
            }
            QComboBox QAbstractItemView::item:hover {
                background-color: #f0f8ff;
            }
            QComboBox QAbstractItemView::item:selected {
                background-color: #e3f2fd;
                color: #1976d2;
            }
            QSlider::groove:horizontal {
                border: 1px solid #cccccc;
                height: 6px;
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #f0f0f0, stop:1 #e0e0e0);
                border-radius: 3px;
            }
            QSlider::handle:horizontal {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #4CAF50, stop:1 #45a049);
                border: 1px solid #cccccc;
                width: 16px;
                margin: -5px 0;
                border-radius: 8px;
            }
            QSlider::handle:horizontal:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #66BB6A, stop:1 #4CAF50);
            }
            QSpinBox {
                border: 2px solid #cccccc;
                border-radius: 4px;
                padding: 3px 5px;
                background-color: white;
                font-size: 12px;
            }
            QSpinBox:hover {
                border-color: #4CAF50;
            }
            QSpinBox:focus {
                border-color: #2196F3;
            }
            QListWidget {
                border: 1px solid #cccccc;
                border-radius: 4px;
                background-color: white;
            }
            QListWidget::item {
                padding: 8px;
                border-bottom: 1px solid #eeeeee;
            }
            QListWidget::item:selected {
                background-color: #e3f2fd;
                color: #1976d2;
            }
            QFrame {
                background-color: white;
                border: 1px solid #dddddd;
                border-radius: 8px;
            }
            QLabel {
                color: #333333;
                border: none;
                background-color: transparent;
            }
            QProgressBar {
                border: 2px solid #cccccc;
                border-radius: 6px;
                text-align: center;
                background-color: #f0f0f0;
            }
            QProgressBar::chunk {
                background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4CAF50, stop:1 #66BB6A);
                border-radius: 4px;
            }
        """)

    # 槽函数实现
    @pyqtSlot()
    def load_default_model(self):
        """自动加载默认模型"""
        default_model_path = os.path.join(self.weights_folder, "1.pt")
        if os.path.exists(default_model_path):
            if self._load_model_file(default_model_path):
                self.model_status_label.setText("已加载: 1.pt")
                self.model_status_label.setStyleSheet("color: green; font-weight: bold;")
                self.load_selected_btn.setText("模型已加载")
                self.load_selected_btn.setEnabled(False)
                self.model_combo.setEnabled(False)
        else:
            print(f"默认模型文件不存在: {default_model_path}")

    @pyqtSlot()
    def load_selected_model(self):
        """加载选中的模型"""
        current_data = self.model_combo.currentData()
        if not current_data:
            QMessageBox.warning(self, "提示", "请先选择一个模型文件")
            return

        if self._load_model_file(current_data):
            selected_name = self.model_combo.currentText()
            self.model_status_label.setText(f"已加载: {selected_name}")
            self.model_status_label.setStyleSheet("color: green; font-weight: bold;")
            self.load_selected_btn.setText("模型已加载")
            self.load_selected_btn.setEnabled(False)
            self.load_custom_btn.setEnabled(False)
            self.model_combo.setEnabled(False)
            self.refresh_models_btn.setEnabled(False)

    def _scan_model_files(self):
        """扫描weights文件夹中的模型文件"""
        self.model_combo.clear()

        if not os.path.exists(self.weights_folder):
            try:
                os.makedirs(self.weights_folder)
                print(f"创建weights文件夹: {self.weights_folder}")
            except Exception as e:
                print(f"创建weights文件夹失败: {e}")

        model_files = []
        if os.path.exists(self.weights_folder):
            pattern = os.path.join(self.weights_folder, "*.pt")
            model_files = glob.glob(pattern)

        if model_files:
            for model_path in sorted(model_files):
                model_name = os.path.basename(model_path)
                self.model_combo.addItem(model_name, model_path)

            if self.model_combo.count() > 0:
                self.model_combo.setCurrentIndex(0)

            self.model_status_label.setText(f"找到 {len(model_files)} 个模型文件")
            self.load_selected_btn.setEnabled(True)
        else:
            self.model_combo.addItem("未找到模型文件", "")
            self.model_status_label.setText(f"在 {self.weights_folder} 中未找到.pt文件")
            self.load_selected_btn.setEnabled(False)

    def _load_model_file(self, file_path: str) -> bool:
        """加载指定的模型文件"""
        try:
            if self.controller.load_model(file_path):
                self._enable_detection_buttons(True)
                return True
            else:
                return False
        except Exception as e:
            QMessageBox.critical(self, "错误", f"模型加载失败: {e}")
            return False

    # 保留原有的load_model方法以兼容
    @pyqtSlot()
    def load_model(self):
        """兼容性方法 - 重定向到手动加载"""
        QMessageBox.warning(self, "提示", "手动选择模型功能已被禁用。")

    # 槽函数实现
    @pyqtSlot()
    def open_single_image(self):
        """打开单张图像"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择图像文件", "",
            "图像文件 (*.jpg *.jpeg *.png *.bmp *.tiff *.tif);;所有文件 (*)")

        if file_path:
            self.controller.open_single_image(file_path)
            self._update_image_list()
            self._display_current_image()  # 确保显示新加载的图像

    @pyqtSlot()
    def open_batch_images(self):
        """批量打开图像"""
        folder_path = QFileDialog.getExistingDirectory(self, "选择图像文件夹")

        if folder_path:
            self.controller.open_batch_images(folder_path)
            self._update_image_list()
            self._display_current_image()  # 确保显示第一张图像

    @pyqtSlot()
    def clear_images(self):
        """清空图像"""
        self.controller.clear_images()
        self.image_list.clear()
        self.image_viewer.clear_image()
        self.current_detection_result = None
        self._update_navigation_buttons()  # 清空后更新按钮状态

    @pyqtSlot()
    def detect_current_image(self):
        """检测当前图像"""
        self.controller.detect_current_image()

    @pyqtSlot()
    def detect_batch_images(self):
        """批量检测图像"""
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        self.detect_batch_btn.setEnabled(False)
        self.controller.detect_batch_async()

    @pyqtSlot(int)
    def _on_image_selected(self, row):
        """图像选择改变"""
        if row >= 0:
            self.controller.set_current_image(row)
            self._display_current_image()
            self._update_navigation_buttons()  # 添加导航按钮状态更新

    @pyqtSlot(int, DetectionResult)
    def _on_detection_completed(self, index, result):
        """检测完成"""
        self.current_detection_result = result
        self._display_current_image()
        self._update_image_list_item(index)
        # self.info_panel.update_detection_info(result)  # 移除这行

    @pyqtSlot(int, int)
    def _on_batch_progress(self, current, total):
        """批量处理进度更新"""
        progress = int((current / total) * 100)
        self.progress_bar.setValue(progress)

    @pyqtSlot()
    def _on_batch_completed(self):
        """批量处理完成"""
        self.progress_bar.setVisible(False)
        self.detect_batch_btn.setEnabled(True)
        self._update_image_list()

        # 显示完成提示弹窗
        image_queue = self.controller.get_image_queue()
        total_images = len(image_queue)
        processed_count = sum(1 for img_info in image_queue if img_info.is_processed)
        total_detections = sum(img_info.detection_result.count
                               for img_info in image_queue
                               if img_info.is_processed and img_info.detection_result)

        # 创建详细的完成信息
        message = f""" 批量检测成功

 总图像数量：{total_images} 张
 成功处理：{processed_count} 张
 检测到天牛：{total_detections} 只
 平均每张：{total_detections / max(processed_count, 1):.1f} 只
"""

        QMessageBox.information(self, "批量检测完成", message)

    @pyqtSlot(str)
    def _on_error_occurred(self, error_msg):
        """错误处理"""
        QMessageBox.critical(self, "错误", error_msg)

    @pyqtSlot(str)
    def _on_status_updated(self, status):
        """状态更新"""
        self.statusBar().showMessage(status)

    def _enable_detection_buttons(self, enabled: bool):
        """启用/禁用检测按钮"""
        self.detect_current_btn.setEnabled(enabled)
        self.detect_batch_btn.setEnabled(enabled)

    def _update_image_list(self):
        """更新图像列表"""
        self.image_list.clear()
        image_queue = self.controller.get_image_queue()

        for i, image_info in enumerate(image_queue):
            item = QListWidgetItem()

            # 显示文件名和处理状态
            status = "✓ 已检测" if image_info.is_processed else "○ 未检测"
            count_info = ""
            if image_info.is_processed and image_info.detection_result:
                count_info = f" ({image_info.detection_result.count}只)"

            item.setText(f"{status} {image_info.filename}{count_info}")
            item.setData(Qt.UserRole, i)

            self.image_list.addItem(item)

        # 选择当前图像
        current_info = self.controller.get_current_image_info()
        if current_info:
            for i in range(self.image_list.count()):
                if self.image_list.item(i).data(Qt.UserRole) == self.controller.image_processor.current_index:
                    self.image_list.setCurrentRow(i)
                    break

        self._update_navigation_buttons()

    def _update_image_list_item(self, index: int):
        """更新特定图像列表项"""
        if 0 <= index < self.image_list.count():
            image_info = self.controller.get_image_queue()[index]
            item = self.image_list.item(index)

            status = "✓ 已检测" if image_info.is_processed else "○ 未检测"
            count_info = ""
            if image_info.is_processed and image_info.detection_result:
                count_info = f" ({image_info.detection_result.count}只)"

            item.setText(f"{status} {image_info.filename}{count_info}")

    def _display_current_image(self):
        """显示当前图像"""
        current_image = self.controller.get_current_image()
        current_info = self.controller.get_current_image_info()

        if current_image is not None and current_info is not None:
            # 如果有检测结果，在图像上绘制边界框
            if current_info.is_processed and current_info.detection_result:
                annotated_image = self._draw_detections(current_image, current_info.detection_result)
                self.image_viewer.display_image(annotated_image)
                # self.info_panel.update_detection_info(current_info.detection_result)  # 移除这行
            else:
                self.image_viewer.display_image(current_image)
                # self.info_panel.update_image_info(current_info)  # 移除这行
        else:
            # 如果没有当前图像，清空显示
            self.image_viewer.clear_image()
            # self.info_panel.clear_info()  # 移除这行

    def _draw_detections(self, image: np.ndarray, result: DetectionResult) -> np.ndarray:
        """在图像上绘制检测结果，支持中文显示"""
        annotated_image = image.copy()

        if not result.boxes:
            return annotated_image

        try:
            # 如果有中文字体，使用PIL绘制中文文本
            if self.font_path:
                return self._draw_detections_with_pil(annotated_image, result)
            else:
                return self._draw_detections_with_opencv(annotated_image, result)
        except Exception as e:
            print(f"绘制检测结果时出错: {e}")
            # fallback到OpenCV绘制英文
            return self._draw_detections_with_opencv(annotated_image, result, use_english=True)

    def _draw_detections_with_pil(self, image: np.ndarray, result: DetectionResult) -> np.ndarray:
        """使用PIL绘制支持中文的检测结果"""
        # 转换为PIL图像
        pil_image = Image.fromarray(image)
        draw = ImageDraw.Draw(pil_image)

        # 根据图像大小调整字体大小
        img_height, img_width = image.shape[:2]
        font_size = max(16, min(img_width, img_height) // 30)

        try:
            font = ImageFont.truetype(self.font_path, font_size)
        except:
            font = ImageFont.load_default()

        for i, box in enumerate(result.boxes):
            # 绘制边界框
            x1, y1, x2, y2 = int(box.x1), int(box.y1), int(box.x2), int(box.y2)

            # 绘制矩形框
            draw.rectangle([x1, y1, x2, y2], outline=(0, 255, 0), width=3)

            # 准备标签文本
            label = f"天牛"

            # 获取文本尺寸
            bbox = draw.textbbox((0, 0), label, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]

            # 绘制文本背景
            bg_x1 = x1
            bg_y1 = y1 - text_height - 8
            bg_x2 = x1 + text_width + 8
            bg_y2 = y1

            # 确保背景框在图像范围内
            bg_y1 = max(0, bg_y1)
            bg_x2 = min(img_width, bg_x2)

            draw.rectangle([bg_x1, bg_y1, bg_x2, bg_y2], fill=(0, 255, 0))

            # 绘制文本
            text_x = x1 + 4
            text_y = bg_y1 + 4
            draw.text((text_x, text_y), label, font=font, fill=(0, 0, 0))

        # 转换回numpy数组
        return np.array(pil_image)

    def _draw_detections_with_opencv(self, image: np.ndarray, result: DetectionResult,
                                     use_english: bool = False) -> np.ndarray:
        """使用OpenCV绘制检测结果"""
        annotated_image = image.copy()

        for box in result.boxes:
            # 绘制边界框
            cv2.rectangle(annotated_image,
                          (int(box.x1), int(box.y1)),
                          (int(box.x2), int(box.y2)),
                          (0, 255, 0), 2)

            # 准备标签
            label = "Beetle"

            # 获取文本尺寸
            font_scale = 0.6
            thickness = 2
            (text_width, text_height), baseline = cv2.getTextSize(
                label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness)

            # 绘制文本背景
            cv2.rectangle(annotated_image,
                          (int(box.x1), int(box.y1) - text_height - 10),
                          (int(box.x1) + text_width, int(box.y1)),
                          (0, 255, 0), -1)

            # 绘制文本
            cv2.putText(annotated_image, label,
                        (int(box.x1), int(box.y1) - 5),
                        cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), thickness)

        return annotated_image

    @pyqtSlot()
    def go_to_previous_image(self):
        """切换到前一张图像"""
        image_queue = self.controller.get_image_queue()
        if not image_queue:
            return

        current_index = self.controller.image_processor.current_index
        if current_index > 0:
            new_index = current_index - 1
            self.controller.set_current_image(new_index)
            self._display_current_image()
            self._update_image_list_selection(new_index)
            self._update_navigation_buttons()

    @pyqtSlot()
    def go_to_next_image(self):
        """切换到后一张图像"""
        image_queue = self.controller.get_image_queue()
        if not image_queue:
            return

        current_index = self.controller.image_processor.current_index
        if current_index < len(image_queue) - 1:
            new_index = current_index + 1
            self.controller.set_current_image(new_index)
            self._display_current_image()
            self._update_image_list_selection(new_index)
            self._update_navigation_buttons()

    def _update_navigation_buttons(self):
        """更新导航按钮状态"""
        image_queue = self.controller.get_image_queue()
        current_index = self.controller.image_processor.current_index

        if not image_queue:
            # 没有图像时禁用所有按钮
            self.prev_image_btn.setEnabled(False)
            self.next_image_btn.setEnabled(False)
            self.image_info_label.setText("无图像")
            return

        total_images = len(image_queue)

        # 更新图像信息显示
        if current_index >= 0:
            current_image_info = image_queue[current_index]
            status = "已检测" if current_image_info.is_processed else "未检测"
            self.image_info_label.setText(f"{current_index + 1} / {total_images} - {status}")
        else:
            self.image_info_label.setText(f"0 / {total_images}")

        # 更新按钮状态
        self.prev_image_btn.setEnabled(current_index > 0)
        self.next_image_btn.setEnabled(current_index < total_images - 1)

    def _update_image_list_selection(self, index: int):
        """更新图像列表选中状态"""
        if 0 <= index < self.image_list.count():
            self.image_list.setCurrentRow(index)